package v1

import (
	"usplatformserver/global"
	"usplatformserver/internal/service"
	"usplatformserver/pkg/app"
	"usplatformserver/pkg/commondata"
	"usplatformserver/pkg/errcode"

	"github.com/gin-gonic/gin"
)

// 输出数据信息
type exportInfo struct {
	FileName string
	Err      *errcode.Error
}

// @Summer 导出数据
// @Produce json
// @Param token header string true "token"
// @Param checkpoint query int true "检查部位"
// @Param patientIds query string true "患者ID列表"
// @Success 200 {object} export.ExportSwaggerSuccess "成功"
// @Failure 400 {object} errcode.Error "请求错误"
// @Failure 500 {object} errcode.Error "内部错误"
// @Router /api/v1/export [get]
func Export(c *gin.Context) {
	param := service.ExportRequest{}
	response := app.NewResponse(c)

	valid, errs := app.BindAndValid(c, &param)
	if !valid {
		response.ToErrorResponse(errcode.InvalidParams.WithDetails(errs.Errors()...))
		return
	}
	svc := service.New(c.Request.Context())

	//导出直接返回
	//getChan := make(chan exportInfo, 1)

	//新建协程并执行
	go getExportData(&svc, &param)

	response.ToResponseSuccess()

	//不用等待协程结束，直接返回导出成功
	// for {
	// 	data := <-getChan
	// 	if data.Err == nil && data.FileName != "" {
	// 		response.ToResponse(gin.H{
	// 			"fileName": data.FileName,
	// 		})
	// 		break
	// 	} else if data.Err != nil {
	// 		response.ToErrorResponse(data.Err)
	// 		break
	// 	}
	// }
	//关闭协程
	//close(getChan)
}

// @Summer 导出数据
// @Produce json
// @Param token header string true "token"
// @Param fileName query string true "文件名"
// @Success 200 {object} model.SwaggerSuccess "成功"
// @Failure 400 {object} errcode.Error "请求错误"
// @Failure 500 {object} errcode.Error "内部错误"
// @Router /api/v1/export [delete]
func DeleteExportFile(c *gin.Context) {
	param := service.DeleteFileRequest{}
	response := app.NewResponse(c)

	valid, errs := app.BindAndValid(c, &param)
	if !valid {
		response.ToErrorResponse(errcode.InvalidParams.WithDetails(errs.Errors()...))
		return
	}
	svc := service.New(c.Request.Context())
	svc.DeleteFile(param.FileName)
	response.ToResponseSuccess()
}

func getExportData(svc *service.Service, param *service.ExportRequest) {
	tarFile, err := svc.GetExportData2(param)

	if err != nil {
		global.MqttClient.ExportFailed(err)
		return
	}
	//插入数据库
	err2 := InsertDownloadFile(*param.Checkpoint, tarFile)
	if err2 != nil {
		global.Logger.Infof("InsertDownloadFile failed: %v", err2)
	}
	//更新内存
	commondata.New().AddWaitDownloadCount(*param.Checkpoint)
	//发送消息
	err2 = global.MqttClient.ExportSuccess(*param.Checkpoint, commondata.New().GetWaitDownloadCount(*param.Checkpoint))
	if err2 != nil {
		global.Logger.Errorf("ExportSuccess failed: %v", err2)
	}
}
